<template>
  <div>
    <h1>User Histories</h1>
    <div class="scroll-container">
      <ul v-if="histories && histories.length">
        <li v-for="history in histories" :key="history.id" class="like-item">
          <!--          {{ history.resourceId }}-->
          <Card :resourceId="history.resourceId" @click="playVideo(history.resourceId)"/>
        </li>
      </ul>
      <p v-else>用户没有观看记录。</p>
    </div>
  </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import {useUserStore} from "@/store/useUserStore"; // 使用用户状态存储
import Card from "@/components/CardOne.vue";
import {useRouter} from "vue-router";
import axios from "axios";

export default {
  components: {Card},
  setup() {
    const userStore = useUserStore();
    const userId = ref(userStore.userInfo?.id); // 获取用户 id
    const histories = ref([]); // 用户的历史记录

    // 获取用户的历史记录
    const fetchUserHistories = async () => {
      try {
        const response = await axios.get(`http://localhost:8000/histories/${userId.value}`);
        histories.value = response.data.data; // 将获取的记录赋值给 histories
        console.log('User Histories:', histories.value);
      } catch (error) {
        console.error('Error fetching user Histories:', error);
      }
    };

    const playVideo = (id) => {
      console.log("播放视频 ID:", id);
      const router = useRouter(); // 获取 router 实例
      router.push({name: 'videoPlayer', params: {resourceId: id}}); // 使用 router 实例
    };

    // 组件挂载时获取用户历史记录
    onMounted(() => {
      if (userId.value) {
        fetchUserHistories();
      } else {
        console.warn('User ID is not defined');
      }
    });

    return {histories, playVideo}; // 返回 histories 和 playVideo 函数
  },
};
</script>

<style scoped>
.scroll-container {
  max-height: 560px; /* 设置容器最大高度 */
  overflow-y: auto; /* 设置垂直滚动条 */
  border: 1px solid #ccc; /* 添加边框 */
  padding: 10px; /* 添加内边距 */
  border-radius: 5px; /* 添加圆角 */
}

ul {
  list-style-type: none;
  padding: 0;
}

.like-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f9f9f9;
}
</style>
